﻿/*
Copyright (c) 2013, SonicLing
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    Redistributions of source code must retain the above copyright notice, this 
list of conditions and the following disclaimer.
    Redistributions in binary form must reproduce the above copyright notice, 
this list of conditions and the following disclaimer in the documentation and/or 
other materials provided with the distribution.
    Neither the name of the SonicLing nor the names of its contributors may be 
used to endorse or promote products derived from this software without specific 
prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace XmlConfiguration
{
	/// <summary>
	/// XML 配置文件的序列化和反序列化操作
	/// </summary>
	public class XmlConfigFile
	{
		/// <summary>
		/// 加载 XML 配置文件到新对象
		/// </summary>
		/// <typeparam name="T">配置类型</typeparam>
		/// <param name="file">配置文件</param>
		/// <returns>配置类型的变量，如果失败则返回默认值</returns>
		public static T Load<T>(string file, Encoding encoding = null)
		{
			if (encoding == null) encoding = Encoding.Unicode;
			if (File.Exists(file))
			{
				return Load<T>(new StreamReader(file, encoding));
			}
			return default(T);
		}

		/// <summary>
		/// 加载 XML 配置到新对象
		/// </summary>
		/// <typeparam name="T">配置类型</typeparam>
		/// <param name="text">配置读取器</param>
		/// <returns>配置</returns>
		public static T Load<T>(TextReader text)
		{
			try
			{
				using (XmlTextReader reader = new XmlTextReader(text))
				{
					try
					{
						XmlSerializer serializer = new XmlSerializer(typeof(T));
						return (T)serializer.Deserialize(reader);
					}
					catch (Exception ex)
					{
						System.Diagnostics.Trace.WriteLine(ex);
					}
				}
			}
			catch (Exception ex)
			{
				System.Diagnostics.Trace.WriteLine(ex);
			}
			return default(T);
		}


		/// <summary>
		/// 加载 XML 配置文件到已有对象
		/// </summary>
		/// <param name="file">XML 配置文件</param>
		/// <param name="obj">配置对象</param>
		/// <returns>是否加载成功</returns>
		/// <param name="encoding">编码</param>
		public static bool Load(string file, IXmlSerializable obj, Encoding encoding = null)
		{
			if (encoding == null) encoding = Encoding.Unicode;
			if (File.Exists(file))
			{
				try
				{
					using (XmlTextReader reader = new XmlTextReader(new StreamReader(file, encoding)))
					{
						try
						{
							obj.ReadXml(reader);
							return true;
						}
						catch (XmlException ex)
						{
							System.Diagnostics.Trace.WriteLine(ex);
						}
					}
				}
				catch (XmlException ex)
				{
					System.Diagnostics.Trace.WriteLine(ex);
				}
			}
			return false;
		}

		/// <summary>
		/// 保存配置到 XML 文件
		/// </summary>
		/// <typeparam name="T">配置类型</typeparam>
		/// <param name="file">XML 文件</param>
		/// <param name="obj">配置对象</param>
		/// <param name="encoding">编码，默认Unicode</param>
		public static void Save<T>(string file, T obj, Encoding encoding = null)
		{
			if (encoding == null) encoding = Encoding.Unicode;
			using (XmlTextWriter writer = new XmlTextWriter(file, encoding))
			{
				writer.Indentation = 4;
				writer.IndentChar = ' ';
				writer.Formatting = Formatting.Indented;
				XmlSerializer serializer = new XmlSerializer(typeof(T));
				try
				{
					serializer.Serialize(writer, obj);
				}
				catch (System.Exception ex)
				{
					System.Diagnostics.Trace.TraceError(ex.ToString());
				}
			}
		}

		/// <summary>
		/// 保存配置到 XML 文件，附带名字空间
		/// </summary>
		/// <typeparam name="T">配置类型</typeparam>
		/// <param name="file">XML 文件</param>
		/// <param name="obj">配置对象</param>
		/// <param name="encoding">编码，默认Unicode</param>
		public static void SaveSerializable<T>(string file, T obj, Encoding encoding = null)
			where T:IXmlSerializable
		{
			if (encoding == null) encoding = Encoding.Unicode;
			using (XmlTextWriter writer = new XmlTextWriter(file, encoding))
			{
				writer.Indentation = 4;
				writer.IndentChar = ' ';
				writer.Formatting = Formatting.Indented;

				writer.WriteProcessingInstruction("xml", "version=\"1.0\"");
				Serialize<T>(obj, writer);
			}
		}

		public static void Serialize<T>(T obj, XmlTextWriter writer) where T : IXmlSerializable
		{
			string rootName = obj.GetType().Name;
			string nameSpace = "";
			{
				XmlRootAttribute[] roots = obj.GetType().GetCustomAttributes(typeof(XmlRootAttribute), true) as XmlRootAttribute[];
				if (roots != null && roots.Length == 1)
				{
					rootName = roots[0].ElementName;
					nameSpace = roots[0].Namespace;
				}
			}
			string prefixName = "";
			string prefixNameSpace = "";
			{
				XmlPrefixAttribute[] roots = obj.GetType().GetCustomAttributes(typeof(XmlPrefixAttribute), true) as XmlPrefixAttribute[];
				if (roots != null && roots.Length == 1)
				{
					prefixName = roots[0].Prefix;
					prefixNameSpace = roots[0].Namespace;
				}
			}

			if (!string.IsNullOrEmpty(prefixName))
			{
				writer.WriteStartElement(string.Format("{0}:{1}", prefixName, rootName));
				if (!string.IsNullOrWhiteSpace(prefixNameSpace))
				{
					writer.WriteAttributeString("xmlns:" + prefixName, prefixNameSpace);
				}
			}
			else
			{
				writer.WriteStartElement(rootName);
			}
			if (!string.IsNullOrWhiteSpace(nameSpace))
			{
				writer.WriteAttributeString("xmlns", nameSpace);
			}

			obj.WriteXml(writer);

			writer.WriteEndElement();
		}

	}
}
